/**
 * timelineSaveProvider
 */
 
  import eventHelper from "../../../util/EventHelper";

  var tool = require("../../../util/tool");
  var consts = require("../../../util/consts");
  var storage = require("../../../util/storage");
  var uuidHelper = require("../../../util/UuidHelper");
  var BaseTimelines = require("../model/BaseTimelines");

  var timelineSaveProvider = (function (){
      var isSaving = false;
      var permission = window.is.options.permission;
      var autoSaveStorages = tool.storage(consts.UNSAVED_TIMELINES_KEY) || {};

      var LOGIN_SYMBOL = 'edtlg';
      var NO_LOGIN_URL = "/web/user/logout?next=/web/user/login?is_session_expired=1";

      var update = function (timeline, callback){
          timeline.uuid = timeline.uuid ? timeline.uuid : uuidHelper.generate();

          var key = timeline.id;
          autoSaveStorages[key] = timeline;
          tool.storage(consts.UNSAVED_TIMELINES_KEY, autoSaveStorages);

          eventHelper.trigger(consts.EVENTS.REQUEST_CHANGED, ["add", timeline.uuid]);

          callback && callback(timeline);
      };

      var checkLoging = function (){
          if (!$.cookie(LOGIN_SYMBOL)){
              window.location = NO_LOGIN_URL;
              return false;
          }
          return true;
      };

      var clearUuids = function (uuids){
          uuids.forEach(function (uuid){
              eventHelper.trigger(consts.EVENTS.REQUEST_CHANGED, ["remove", uuid]);
          });
      };

      var save = function (){
          if (!checkLoging()) return;

          // admin查看AR进入不保存数据
          if (permission == consts.PERMISSION_READONLY) return;

          autoSaveStorages = tool.storage(consts.UNSAVED_TIMELINES_KEY) || {};

          if (!tool.isEmptyObject(autoSaveStorages) && !isSaving){
              console.log("自动保存中...");

              isSaving = true;

              var autoSaveTimelines = [], uuids = [];
              for (var key in autoSaveStorages){
                  var timeline = autoSaveStorages[key];
                  if (timeline.uuid) uuids.push(timeline.uuid);

                  delete timeline.uuid;

                  autoSaveTimelines.push(timeline);
              }

              BaseTimelines.updateAllTimelines(autoSaveTimelines, function (){
                  console.log("保存成功");
                  isSaving = false;

                  autoSaveStorages = {};
                  tool.storage(consts.UNSAVED_TIMELINES_KEY, autoSaveStorages);

                  clearUuids(uuids);
              }, function (){
                  console.log("保存失败");
                  isSaving = false;
                  clearUuids(uuids);
              });
          }
      };

      return {
          save: save,
          update: update
      }
  })();

  module.exports = timelineSaveProvider;
